<!-- Login.vue -->
<template>
  <div>
    <h2>Login_JWT</h2>
    <form @submit.prevent="handleLogin">
      <div>
        <label for="username">Username:</label>
        <input type="text" v-model="username" id="username" required />
      </div>
      <div>
        <label for="password">Password:</label>
        <input type="password" v-model="password" id="password" required />
      </div>
      <button type="submit">Login</button>
    </form>
    <p v-if="error">{{ error }}</p>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import axios from 'axios'

const username = ref('')
const password = ref('')
const error = ref('')

const handleLogin = async () => {
  try {
    const response = await axios.post('http://localhost:3000/login', {
      username: username.value,
      password: password.value,
    })

    if (response.data.success) {
      localStorage.setItem('token', response.data.token)
      alert('Logged in successfully')
      console.log('localStorage中的token是', localStorage)

      // 重定向到用户个人资料页面
      window.location.href = '/profile'
    } else {
      error.value = 'Invalid credentials'
    }
  } catch (err) {
    error.value = 'An error occurred'
  }
}
</script>
